// 检测任务的标注结果
import labelDef from './Def';
import LabelDetection from '../detection/Label';
export default class LabelCaption extends LabelDetection {
    // 构造函数
    constructor(label_format) {
        super(label_format);
        this.selected_label_id = -1;
        this.captionPanelVisible = true;
        this.isDragging = false;
        this.lastPos = { x: 0, y: 0 };
    }

    bindCanvas(canvas, image, label_tools) {
        super.bindCanvas(canvas, image, label_tools);
        this.captionPanelVisible = true;

        // 创建看板组
        this.captionPanel = new fabric.Group([], {
            selectable: false,
            evented: false,
            visible: this.captionPanelVisible
        });
        this.canvas.add(this.captionPanel);

        if (this.labels.length > 0) {
            this.selected_label_id = 0;
            let label = this.labels[0];
            this.drawCaptionPanel(label);
        }
    }

    drawCaptionPanel(label) {
        if (!this.captionPanelVisible || !label || !label.data?.caption) {
            if (this.captionPanel) {
                this.captionPanel.visible = false;
                this.canvas.requestRenderAll();
            }
            return;
        }

        // 清除旧内容
        if (this.captionPanel) {
            this.canvas.remove(this.captionPanel);
        }

        // 固定尺寸参数
        const padding = 5;
        const maxLines = 5;
        const lineHeight = 24;
        const borderWidth = 2;
        const panelWidth = 400;
        const textMaxWidth = 360;

        // 获取canvas当前状态
        const zoom = this.canvas.getZoom();
        const vpt = this.canvas.viewportTransform;

        // 计算实际使用的尺寸
        const lines = this.wrapText(label.data.caption, textMaxWidth / zoom, maxLines).slice(0, maxLines);
        const panelHeight = Math.min(lines.length * lineHeight + 15, maxLines * lineHeight + 15);

        // 优化位置计算 - 使用canvas的viewportToAbsolute方法
        const fixedLeft = (padding - vpt[4]) / zoom;
        const fixedTop = (padding + 40 - vpt[5]) / zoom;

        // 创建所有元素（使用相同的基准点）
        const backgroundRect = new fabric.Rect({
            left: fixedLeft,
            top: fixedTop,
            width: panelWidth,
            height: panelHeight,
            fill: 'rgba(5, 5, 174, 0.6)',
            stroke: '#000033',
            strokeWidth: borderWidth,
            selectable: false,
            evented: false,
            scaleX: 1 / zoom,
            scaleY: 1 / zoom,
            originX: 'left',
            originY: 'top'
        });

        const textObjects = lines.map((line, index) => {
            return new fabric.Text(line, {
                left: fixedLeft + 10 / zoom, // 缩放补偿
                top: fixedTop + 10 / zoom + index * (lineHeight / zoom),
                fontSize: 14,
                fontFamily: 'Arial',
                fill: '#fff',
                selectable: false,
                evented: false,
                textAlign: 'left',
                originX: 'left',
                originY: 'top',
                scaleX: 1 / zoom,
                scaleY: 1 / zoom
            });
        });

        // 创建新Group并添加所有元素
        // 创建新Group并添加所有元素
        this.captionPanel = new fabric.Group([
            backgroundRect,
            ...textObjects
        ], {
            selectable: true,  // 改为可选中
            evented: true,     // 改为可交互
            visible: true,
            originX: 'left',
            originY: 'top',
            hasBorders: false,
            hasControls: false, // 隐藏默认控制点
            lockRotation: true // 锁定旋转
        });

        // 添加点击事件
        this.captionPanel.on('mousedown', (e) => {
            this.isDragging = false;
            this.lastPos = { x: e.e.clientX, y: e.e.clientY };
        });

        this.captionPanel.on('mousemove', (e) => {
            if (this.lastPos.x !== 0 && this.lastPos.y !== 0) {
                const dx = Math.abs(e.e.clientX - this.lastPos.x);
                const dy = Math.abs(e.e.clientY - this.lastPos.y);
                if (dx >= 1 || dy >= 1) { // 移动超过5像素视为拖拽
                    this.isDragging = true;
                }
            }
        });

        this.captionPanel.on('mouseup', (e) => {
            if (!this.isDragging && e.target === this.captionPanel && this.label_panel) {
                this.label_panel.showEditDialog('caption', label.id, (form) => {
                    this.updateLabel(form);
                    this.label_panel.updateLabel(label);
                    this.drawCaptionPanel(label);
                });
            }
            this.isDragging = false;
            this.lastPos = { x: 0, y: 0 };
        });

        // 添加到画布
        this.canvas.add(this.captionPanel);
        this.canvas.requestRenderAll();
    }

    wrapText(text, maxWidth, maxLines = 3) {
        if (!text || typeof text !== 'string') return [];

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        // 使用与渲染时相同的字体设置
        ctx.font = '14px Arial, "PingFang SC", "Microsoft YaHei"';

        const isCJK = (char) => {
            const code = char.charCodeAt(0);
            return (code >= 0x4E00 && code <= 0x9FFF) ||
                (code >= 0x3040 && code <= 0x30FF) ||
                (code >= 0xAC00 && code <= 0xD7AF);
        };

        let lines = [];
        let currentLine = '';

        // 预处理：将文本拆分为可分割单元
        const segments = [];
        let currentSegment = '';

        for (let i = 0; i < text.length; i++) {
            const char = text[i];
            if (isCJK(char)) {
                if (currentSegment) segments.push(currentSegment);
                segments.push(char);
                currentSegment = '';
            } else if (char === ' ') {
                if (currentSegment) segments.push(currentSegment);
                segments.push(' ');
                currentSegment = '';
            } else {
                currentSegment += char;
            }
        }
        if (currentSegment) segments.push(currentSegment);

        // 精确计算每行内容（考虑缩放因素）
        for (const segment of segments) {
            const testLine = currentLine + segment;
            const metrics = ctx.measureText(testLine);

            // 调整后的最大宽度计算（考虑缩放）
            const adjustedMaxWidth = maxWidth * this.canvas.getZoom();

            if (metrics.width > adjustedMaxWidth) {
                if (currentLine) lines.push(currentLine);
                currentLine = segment.trim();

                // 处理超长内容（强制分割）
                if (ctx.measureText(segment).width > adjustedMaxWidth) {
                    for (let i = 0; i < segment.length; i++) {
                        const char = segment[i];
                        const testChar = currentLine + char;
                        if (ctx.measureText(testChar).width > adjustedMaxWidth) {
                            lines.push(currentLine);
                            currentLine = char;
                        } else {
                            currentLine += char;
                        }
                    }
                }
            } else {
                currentLine = testLine;
            }
        }

        if (currentLine) lines.push(currentLine);
        return lines.slice(0, maxLines);
    }

    selectLabel(label_id, target = null) {
        this.selected_label_id = label_id;
        if (this.labels[label_id]) {
            this.drawCaptionPanel(this.labels[label_id]);
        }
        this.canvas.requestRenderAll();
    }

    ///========================以下定义数据相关的处理函数========================
    // 新增标注结果
    addLabel(data) {
        // console.log('LabelCaption addLabel data = ', data);
        this.labels[data.id] = this.labelOfBase(data.id, 'vision:caption', labelDef(data));
        this.saved = false;
        return true;
    }

    fromJson(json_data) {
        // console.log('LabelCaption::fromJson json_data = ', json_data);
        this.labels = [];
        for (let i = 0; i < json_data.length; i++) {
            let data = json_data[i];
            this.labels[data.id] = this.labelOfBase(data.id, 'vision:caption', data);
        }
    }
}
